/**
 * Created by leo on 2/2.
 */
angular.module('panels')
    .directive('panelBomUntreatedAlarmStatistics', function ($http, loadConf, $timeout, $log, tabService) {
        return {
            scope: {},
            link: function (scope) {
                function gradientColor(color) {
                    return {
                        radialGradient: {cx: 0.5, cy: 0.3, r: 0.7},
                        stops: [
                            [0, color],
                            [1, Highcharts.Color(color).brighten(-0.1).get('rgb')] // darken
                        ]
                    };
                }

                function getHighChartOptions(store, categories) {
                    return {
                        chart: {
                            type: 'bar'
                        },
                        title: {
                            text: ''
                        },
                        xAxis: {
                            categories: categories
                        },
                        yAxis: {
                            min: 0,
                            title: {
                                text: '告警',
                                enabled: false
                            }
                        },
                        legend: {
                            reversed: true
                        },
                        plotOptions: {
                            series: {
                                stacking: 'normal'
                            },
                            bar: {
                                point: {
                                    events: {}
                                }
                            }
                        },
                        series: [{// 1:'#DD4444', 2: '#FF7F50', 3: '#0078E7'
                            name: '一般',
                            color: gradientColor('#0078E7'),
                            data: store[3],
                            cursor: 'pointer'
                        }, {
                            name: '重要',
                            color: gradientColor('#FF7F50'),
                            data: store[2],
                            cursor: 'pointer'
                        }, {
                            name: '严重',
                            color: gradientColor('#DD4444'),
                            data: store[1],
                            cursor: 'pointer'
                        }]
                    };
                }

                scope.options = getHighChartOptions({1: [], 2: [], 3: []}, []);
                scope.panelTitle = '未处理告警统计';
                loadConf('panel-bom-untreated-alarm-statistics.yml').then(function (setting) {
                    scope.more = setting.more;
                    scope.tabs = setting.tabs;
                    scope.tabs.currentTab = setting.tabs[0];
                    var preData, timeoutId;
                    scope.$on('$destroy', function () {
                        timeoutId && $timeout.cancel(timeoutId);
                    });
                    (function updateData() {
                        $http.jsonp(scope.tabs.currentTab.countQueryUrl)
                        // 处理统计数据
                            .then(function (resp) {
                                if (angular.equals(resp.data, preData)) return false;
                                preData = resp.data;
                                var data = angular.copy(resp.data);
                                var categories = [],
                                    store = {1: [], 2: [], 3: []},
                                    eventCountsArray = [];
                                angular.forEach(data, function (eventCounts, key) {
                                    eventCountsArray.push(eventCounts);
                                    eventCounts["key"] = key;
                                });
                                // 按告警权重对业务系统排序
                                eventCountsArray = eventCountsArray.sort(function (a, b) {
                                    /**
                                     * 告警权重的计算公式 ∑((4-eventClass)^2 * eventCount)
                                     * @param counts
                                     * @returns {number}
                                     */
                                    var weight = function (counts) {
                                        var weight = 0;
                                        angular.forEach(counts, function (count, eventClass) {
                                            eventClass = parseInt(eventClass);
                                            if (!isNaN(eventClass)) {
                                                weight += (4 - eventClass) * (4 - eventClass) * counts[eventClass]
                                            }
                                        });
                                        return weight;
                                    };
                                    return weight(a) < weight(b);
                                });
                                for (var i = 0; i < eventCountsArray.length; i++) {
                                    var eventCounts = eventCountsArray[i],
                                        key = eventCounts.key;
                                    categories.push(key.split(':')[1]);
                                    angular.forEach(store, function (seriesData, eventClass) {
                                        seriesData.push(parseInt(eventCounts[eventClass]) || 0);
                                    });
                                    // 做多展示5个业务系统（高度有限）
                                    if (categories.length == (setting.maxColumnsAllowed || 5)) break;
                                }
                                // 通知更新charts
                                scope.options = getHighChartOptions(store, categories);
                                scope.options.plotOptions.bar.point.events.click = function () {
                                    tabService.addTab({
                                        name: '未处理告警-' + this.category,
                                        url: scope.tabs.currentTab.viewUrl.replace(/\{name\}/ig, this.category)
                                    });
                                };
                            }).then(callback, callback);
                        function callback() {
                            if (setting.updateInterval > 0) {
                                timeoutId = $timeout(updateData, setting.updateInterval * 1000);
                            }
                        }

                        scope.changeTab = function (tab) {
                            $timeout.cancel(timeoutId);
                            scope.tabs.currentTab = tab;
                            updateData();
                        };

                        $log.debug('panel update data: bom-untreated-alarm-statistics');
                    }());
                });
            },
            templateUrl: 'app/panel/bom/untreated-alarm-statistics.html'
        };
    });